<template>
  <div class="learn-detail">
    <div class="player-container">
      <div class="player-header">
        <h1 :title="lesson.name" class="video-title">
          <span class="title">{{lesson.name}}</span>
        </h1>
        <div class="video-data">
          <span :title="(lesson.learnNum || 0) + '人在学'" class="video-data-item">{{lesson.learnNum || 0}}人在学</span>
          <span title="收藏数" class="video-data-item">{{lesson.favoriteCount ? lesson.favoriteCount : 0}}收藏</span>
          <span class="video-data-item">{{lesson.startTime}}</span>
        </div>
      </div>
      <div class="player-content">
        <div class="player-content-header">
          <el-row class="row">
            <el-col class="left" :span="showListBox ? 18 : 24">
              <div class="player" v-if="videoLink">
                <video-player :player-play="playerPlay" :player-pause="playerPause" :player-ended="playerEnded" :player-playing="playerPlaying" :player-timeupdate="playerTimeupdate" style="height: 100%;width: 100%;" :src="videoLink"/>
              </div>
              <div class="sign-up-layer" v-else>
                <div class="sign-up-button-cnt">
                  <div class="sign-up-button" v-if="!isLogin">
                    <el-button @click="startLearn" class="el-icon-video-play button">登录学习</el-button>
                  </div>
                  <div class="sign-up-button" v-else-if="lesson.signUp && lesson.signUp.id">
                    <el-button @click="startLearn" class="el-icon-video-play button">继续学习</el-button>
                  </div>
                  <div class="sign-up-button" v-else>
                    <el-button @click="startLearn" class="el-icon-video-play button">开始学习</el-button>
                  </div>
                </div>
                <img :src="lesson.image" style="width: 100%;height: 100%;"/>
              </div>
              <div class="unfold" @click="listBoxArrow">
                <div class="arrow-wrap" :title="showListBox ? '收起列表' : '展开列表'">
                  <div class="arrow">
                    <i class="el-icon-arrow-right" :class="{'el-icon-arrow-left': !showListBox}"></i>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col class="right" :span="6" v-if="showListBox">
              <div class="scroll-area">
                <div class="anthology-content-scroll">
                  <div class="anthology-content">
                    <div class="detail-item">
                      <el-menu class="el-menu-vertical" :default-openeds="defaultOpenedIndexList" :default-active="menuDefaultActive">
                        <el-submenu :index="index + ''" v-for="(lessonChapter, index) in lessonChapterList" :key="index">
                          <template #title>
                            <div class="slot-title" :title="lessonChapter.title">{{lessonChapter.title}}</div>
                          </template>
                          <el-menu-item :key="i" @click="videoChange(chapterSection)" :index="index + '-' + i" v-for="(chapterSection, i) in lessonChapter.chapterSectionList">
                            <template #title>
                              <div class="message-item-content" :title="chapterSection.title">
                                <i class="el-icon-video-play"></i>
                                {{chapterSection.title}}
                              </div>
                            </template>
                          </el-menu-item>
                        </el-submenu>
                      </el-menu>
                    </div>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="player-content-bottom">
          <ul class="play-fn">
            <li class="play-fn-li">
              <a href="javascript:void(0);" @click="memberLike" :class="{'custom-active': lesson.like && lesson.like.status}">
                <i class="el-icon-thumb"></i>
                点赞 <span style="color: #cccccc;">{{lesson.likeCount}}</span>
              </a>
            </li>
            <li class="play-fn-li">
              <a href="javascript:void(0);" @click="memberFavorite" :class="{'custom-active': lesson.favorite && lesson.favorite.id}">
                <i class="el-icon-star-off"></i>
                收藏 <span style="color: #cccccc;">{{lesson.favoriteCount}}</span>
              </a>
            </li>
            <li class="play-fn-li">
              <a href="javascript:void(0);" @click="showHomework">
                <i class="el-icon-tickets"></i>
                作业
              </a>
            </li>
            <li class="play-fn-li">
              <a target="_blank" :href="'/learn/certificate?lessonId=' + lesson.id + '&signUpId=' + (lesson.signUp ? lesson.signUp.id : '')">
                <i class="el-icon-money"></i>
                证书
              </a>
            </li>
          </ul>
          <el-dialog v-model="homeworkDialog" width="800px" :before-close="hideHomework">
            <homework v-if="homeworkDialog" :lesson="lesson" :callback="hideHomework"/>
            <template #footer>
              <div class="dialog-footer">
                <el-button type="text" @click="hideHomework">关闭</el-button>
              </div>
            </template>
          </el-dialog>
        </div>
      </div>
    </div>
    <div class="learn-desc">
      <div class="title-item">课程概述</div>
      <div>
        <el-row class="row">
          <el-col :span="showListBox ? 18 : 24">
            <div style="line-height: 28px;" v-html="lesson.introduction"></div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="comment">
      <div class="title-item">评论</div>
      <comment-list topic-type="lesson" :topic-id="lesson.id"/>
    </div>
    <Login :show="showLoginFlag" @callback="loginCallback" @success="successCallback"/>
  </div>
</template>

<script>
  import {ref} from "vue"
  import { getToken } from "../../../util/tokenUtils"
  import {
    getLesson,
    getLessonChapterList,
    saveSignUp,
    saveRecord,
    updateRecord,
  } from "../../../api/learn/lesson"
  import videoPlayer from "../../../components/Video/index"
  import commentList from "../../comment/list"
  import {like, getMemberLikeList, getLikeCountList} from "../../../api/comment/like"
  import {favorite, getMemberFavoriteList, getFavoriteCountList} from "../../../api/comment/favorite"
  import {useRoute} from "vue-router";
  import Homework from "@/views/learn/homework";
  export default {
    name: "learnDetail",
    components: {
      Homework,
      videoPlayer,
      commentList
    },
    setup() {
      const lesson = ref({
        code: "",
        endTime: "",
        id: 0,
        image: "",
        introduction: "",
        isShow: true,
        name: "",
        phrase: "",
        startTime: ""
      })
      const lessonChapterList = ref([])
      const showListBox = ref(true)
      const videoLink = ref("")
      const defaultOpenedIndexList = ref([])
      const showLoginFlag = ref(false)
      const recordIntervalObj = ref()
      const currentChapterSection = ref({})
      const isLogin = ref(getToken())
      const menuDefaultActive = ref("")
      const route = useRoute()

      const position = function() {
        const position = route.query.position
        // 页面内定位
        if (position && position === "comment") {
          const anchor = undefined// $el.querySelector(".comment");
          console.log(anchor)
          setTimeout(function () {
            document.body.scrollTop = anchor.offsetTop
            console.log(anchor.offsetTop)
            console.log(document.body.scrollTop)
            document.documentElement.scrollTop = anchor.offsetTop
          }, 500)
        }
      }
      const getRecordChapterSection = function() {
        // 已学习章节
        let recordChapterSectionIdList = []
        if (lesson.value.recordList && lesson.value.recordList.length) {
          for (const record of lesson.value.recordList) {
            if (recordChapterSectionIdList.indexOf(record.lessonChapterSectionId) === -1) {
              recordChapterSectionIdList.push(record.lessonChapterSectionId)
            }
          }
        }
        let section
        let chapterIndex = 0;
        let chapterSectionIndex;
        for (const lessonChapter of lessonChapterList.value) {
          chapterSectionIndex = 0
          for (const chapterSection of lessonChapter.chapterSectionList) {
            // 第一个没有学习的章节
            if (recordChapterSectionIdList.indexOf(chapterSection.id) === -1) {
              section = chapterSection
              break;
            }
            chapterSectionIndex++
          }
          if (section) {
            break
          }
          chapterIndex++
        }
        // 全部章节都已经学习，那么选择第一个章节
        if (!section) {
          section = lessonChapterList.value[0].chapterSectionList[0]
          chapterIndex = 0
          chapterSectionIndex = 0
        }
        menuDefaultActive.value = chapterIndex + "-" + chapterSectionIndex
        if (section) {
          currentChapterSection.value = section
        } else {
          currentChapterSection.value = lessonChapterList.value[0].chapterSectionList[0]
        }
      }
      const loadLike = function() {
        getLikeCountList({topicIdList: lesson.value.id, topicType: "lesson"}, res => {
          if (res && res.length) {
            lesson.value.likeCount = res[0].num;
          } else {
            lesson.value.likeCount = ""
          }
        })
        if(getToken()) {
          getMemberLikeList({topicIdList: lesson.value.id, topicType: "lesson"}, res => {
            if (res && res.length) {
              lesson.value.like = res[0];
            } else {
              lesson.value.like = null
            }
          })
        }
      }
      const loadFavorite = function() {
        getFavoriteCountList({topicIdList: lesson.value.id, topicType: "lesson"}, res => {
          if (res && res.length) {
            lesson.value.favoriteCount = res[0].num;
          } else {
            lesson.value.favoriteCount = ""
          }
        })
        if(getToken()) {
          getMemberFavoriteList({topicIdList: lesson.value.id, topicType: "lesson"}, res => {
            if (res && res.length) {
              lesson.value.favorite = res[0];
            } else {
              lesson.value.favorite = null
            }
          })
        }
      }
      const load = function() {
        const id = route.query.id
        lesson.value.id = id ? parseInt(id) : 0;
        if (id) {
          getLesson(id, (res) => {
            res.likeCount = ""
            res.like = {}
            res.favorite = {}
            lesson.value = res
            getLessonChapterList({lessonId: res.id}, r => {
              lessonChapterList.value = r.list
              if (r.list.length) {
                for (let i = 0; i < r.list.length; i++) {
                 defaultOpenedIndexList.value.push(i + "");
                }
              }
              // 获取当前学习到的课程
              getRecordChapterSection()
              position()
            })
            // 加载点赞信息
            loadLike()
            // 加载收藏信息
            loadFavorite()
          })
        }
      }
      load()
      const listBoxArrow = function() {
        showListBox.value = !showListBox.value;
      }
      const signUp = function(success) {
        if (!getToken()) {
          showLoginFlag.value = true
          return
        }
        saveSignUp({lessonId: lesson.value.id}, res => {
          console.log(res)
          lesson.value.signUp = res
          success && success(res)
        })
      }
      let maxProgressTime = 0;
      const record = function(learnTime) {
        if (currentChapterSection.value) {
          console.log("最大播放的时间", maxProgressTime)
          const param = {
            lessonId: lesson.value.id,
            lessonChapterSectionId: currentChapterSection.value.id,
            signUpId: lesson.value.signUp.id,
            learnTime: learnTime,
            maxProgressTime: maxProgressTime
          }
          console.log(param)
          // 判断是否已经存在学习记录
          let existsRecord = undefined;
          let existsRecordIndex = 0;
          if (lesson.value.recordList) {
            for (const record of lesson.value.recordList) {
              if (record.lessonId === param.lessonId
                      && record.lessonChapterSectionId === param.lessonChapterSectionId
                      && record.signUpId === param.signUpId) {
                existsRecord = record;
                break
              }
              existsRecordIndex++
            }
          }
          // 修改学习记录
          if (existsRecord) {
            param.id = existsRecord.id;
            updateRecord(param, res => {
              console.log(res)
              lesson.value.recordList[existsRecordIndex] = res
            })
          }
          // 新增学习记录
          else {
            saveRecord(param, res => {
              console.log(res)
              if (!lesson.value.recordList || !lesson.value.recordList.length) {
                lesson.value.recordList = []
              }
              lesson.value.recordList.push(res)
            })
          }
        }
      }
      let recordTime = 0;
      let recordUploadInterval;
      // 清除学习记录定时器
      const clearRecordInterval = function() {
        console.log("上传学习秒数", recordTime)
        // 上传学习记录
        record(recordTime)
        // 学习记录清0
        recordTime = 0;
        if (recordIntervalObj.value) {
          clearInterval(recordIntervalObj.value)
        }
        if (recordUploadInterval) {
          clearInterval(recordUploadInterval)
        }
      }
      // 定时上传学习记录
      const recordInterval = function() {
        clearRecordInterval()
        // 一秒一次
        recordIntervalObj.value = setInterval(() => {
          recordTime += 1
        }, 1000);
        // 20秒定时上传一次
        recordUploadInterval = setInterval(() => {
          console.log("定时上传学习秒数", recordTime)
          // 上传学习记录
          record(recordTime)
          // 学习记录清0
          recordTime = 0;
        }, 5000);
      }
      const videoChange = function(chapterSection) {
        console.log("改变视频，先上传之前的视频记录");
        // 改变视频，先上传之前的视频记录
        clearRecordInterval()
        // 没有登录
        if (!getToken()) {
          showLoginFlag.value = true
          return
        }
        // 没有报名记录，报名并开始学习
        if (!lesson.value.signUp || !lesson.value.signUp.id) {
          // 报名
          signUp(() => {
            currentChapterSection.value = chapterSection;
            // 当前播放的章节 第一个
            videoLink.value = currentChapterSection.value.url
          })
        } else {
          currentChapterSection.value = chapterSection;
          // 当前播放的章节 第一个
          videoLink.value = currentChapterSection.value.url;
        }
      }
      const startLearn = function() {
        // 没有登录
        if (!getToken()) {
          showLoginFlag.value = true
          return
        }
        // 没有报名记录，报名并开始学习
        if (!lesson.value.signUp || !lesson.value.signUp.id) {
          // 报名
          signUp(() => {
            // 当前播放的章节 第一个
            currentChapterSection.value = lessonChapterList.value[0].chapterSectionList[0]
            videoLink.value = currentChapterSection.value.url
          })
        }
        // 继续学习
        else {
          getRecordChapterSection()
          videoLink.value = currentChapterSection.value.url
        }
      }
      const playerPlay = function() {
        // 开始上传记录
        console.log("开始播放，启用计时器")
        // 开启定时器
        recordInterval();
      }
      const playerPause = function() {
        console.log("暂停，清除计时器")
        // 暂停上传记录
        clearRecordInterval()
      }
      const playerEnded = function() {
        console.log("结束，清除计时器")
        // 暂停上传记录
        clearRecordInterval()
      }
      const playerPlaying = function () {
        console.log("播放，启用计时器")
        // 开始上传记录
        //recordInterval();
      }
      const playerTimeupdate = (player) => {
        maxProgressTime = parseInt(player.currentTarget.currentTime)
        console.log(maxProgressTime)
      }
      const loginCallback = function() {
        showLoginFlag.value = false
      }
      const successCallback = function() {
        showLoginFlag.value = false
      }
      const memberLike = function() {
        like(lesson.value, "lesson")
      }
      const memberFavorite = function() {
        favorite(lesson.value, "lesson")
      }
      const homeworkDialog = ref(false)
      const hideHomework = () => {
        homeworkDialog.value = false
      }
      const showHomework = () => {
        homeworkDialog.value = true
      }
      return {
        lesson,
        lessonChapterList,
        showListBox,
        videoLink,
        defaultOpenedIndexList,
        showLoginFlag,
        recordIntervalObj,
        currentChapterSection,
        isLogin,
        menuDefaultActive,
        listBoxArrow,
        videoChange,
        playerPlay,
        playerPause,
        playerEnded,
        playerPlaying,
        playerTimeupdate,
        loginCallback,
        successCallback,
        memberLike,
        memberFavorite,
        startLearn,
        homeworkDialog,
        hideHomework,
        showHomework,
      }
    }
  }
</script>

<style lang="scss" scoped>
  .learn-detail {
    width: calc(100% - 20px);
    margin: 0 auto;
  }
  .player-content-bottom {
    ::v-deep .el-dialog__body {
      padding-top: 10px;
    }
  }
  .player-container {
    position: relative;
    margin: 30px auto;
    background: #ffffff;
    padding: 30px 30px 0;
    border-radius: 10px;
    .player-header {
      border: 0;
      font-size: 100%;
      vertical-align: baseline;
      height: 70px;
      box-sizing: border-box;
      margin-top: 0;
      .video-title {
        padding: 0;
        border: 0;
        vertical-align: baseline;
        font-size: 18px;
        font-weight: 500;
        color: #212121;
        height: 26px;
        margin: 0 0 8px 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        .title {
          margin: 0;
          padding: 0;
          border: 0;
          font-size: 100%;
          vertical-align: middle;
        }
      }
      .video-data {
        margin: 0;
        padding: 0;
        border: 0;
        vertical-align: baseline;
        font-size: 12px;
        height: 16px;
        color: #999;
        display: -ms-flexbox;
        display: flex;
        -ms-flex-align: center;
        align-items: center;
        text-overflow: ellipsis;
        white-space: nowrap;
        .video-data-item {
          padding: 0;
          border: 0;
          font-size: 100%;
          vertical-align: baseline;
          display: inline-block;
          height: 16px;
          margin-right: 12px;
        }
        .video-data-item:last-child {
          margin: 0;
        }
      }
    }
    .player-content {
      position: relative;
      width: 100%;
      .player-content-header {
        .left {
          .player {
            background-color: #ccc;
          }
          .sign-up-layer {
            width: 100%;
            background-color: #000;
            position: relative;
            height: 560px;
            .sign-up-button-cnt {
              position: absolute;
              width: 100%;
              height: 100%;
              z-index: 999;
              background: rgba(0, 0, 0, .7);
            }
            .sign-up-button {
              width: auto;
              height: 96px;
              border-radius: 50%;
              color: $--color-primary;
              text-align: center;
              line-height: 96px;
              /*background-color: #23b8ff;*/
              position: absolute;
              z-index: 1;
              left: 50%;
              top: 50%;
              -webkit-transform: translate(-50%,-50%);
              -ms-transform: translate(-50%,-50%);
              transform: translate(-50%,-50%);
              cursor: pointer;
              .button {
                font-size: 18px;
                color: #fff;
                background-color: $--color-primary;
                border: 0;
              }
            }
          }
          .unfold {
            position: absolute;
            z-index: 1;
            width: 20px;
            height: 40px;
            top: 40%;
            right: -20px;
            background: #cccccc;
            border-radius: 0 111.11px 111.11px 0;
            cursor: pointer;
            .arrow-wrap {
              display: block;
              height: 100%;
              position: relative;
              .arrow {
                margin-top: 10px;
                color: rgba(255, 255, 255, 0.6);
              }
            }
          }
        }
        .right {
          .anthology-wrap {
            height: 100%;
            background-color: #1e1e24;
          }
          .slot-title{
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            width: calc(100% - 15px);
          }
          .message-item-content {
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
          }
          .scroll-area {
            float: left;
            width: 100%;
            scrollbar-track-color: #1f1f1f;
            scrollbar-arrow-color: #1f1f1f;
            scrollbar-base-color: #1f1f1f;
            scrollbar-face-color: #979797;
            scrollbar-3dlight-color: #979797;
            scrollbar-highlight-color: #979797;
            scrollbar-shadow-color: #979797;
            height: 100%;
            position: absolute;
            overflow: auto;
            top: 0;
            right: 0;
            background-color: #f5f5f5;
            .anthology-content-scroll {
              width: 100%;
              margin: 0 auto;
              .anthology-content {

              }
            }
          }
        }
      }
      .player-content-bottom {
        height: 56px;
        display: inline-block;
        width: 100%;
        .play-fn {
          position: relative;
          z-index: 1000;
          height: 56px;
          line-height: 56px;
          padding: 0;
          float: left;
          width: 360px;
          li {
            list-style: none;
            display: inline-block;
            position: relative;
            margin-right: 12px;
            color: hsla(0,0%,100%,.6);
            font-size: 14px;
            height: 32px;
            line-height: 32px;
            border-radius: 16px;
            padding: 0 12px;
            a {
              cursor: pointer;
              color: #2a2a32;
              text-decoration: none;
              display: block;
            }
          }
          .play-fn-li {
            a:hover {
              color: $--color-primary!important;
            }
            .custom-active {
              color: $--color-primary!important;
              i {
                color: $--color-primary!important;
              }
            }
          }
        }
      }
    }
  }
  .learn-desc {
    margin: 30px 0;
    background: #fff;
    padding: 30px;
    border-radius: 10px;
    .title-item {
      font-size: 20px;
      line-height: 24px;
      height: 24px;
      margin-bottom: 16px;
      color: #000000;
    }
  }
  .comment {
    margin: 30px 0;
    background: #fff;
    padding: 30px;
    border-radius: 10px;
    .title-item {
      font-size: 20px;
      line-height: 24px;
      height: 24px;
      margin-bottom: 16px;
      color: #000000;
    }
  }
</style>
<style lang="scss">
  .detail-item {
    .el-menu {
      border: 0;
      .el-submenu__title, .el-menu-item {
        background: #f5f5f5;
      }
    }
  }
</style>
